/*
 * Copyright Aduna (http://www.aduna-software.com/) (c) 1997-2007.
 *
 * Licensed under the Aduna BSD-style license.
 */

package edu.tju.commons.text;

import java.io.Serializable;
import java.text.Collator;
import java.util.Comparator;
import java.util.Locale;
import java.util.Map;
import java.util.WeakHashMap;

/**
 * Comparator that compares the String representations of two objects (using
 * their toString() methods).
 * 
 * @author Herko ter Horst
 * 
 */
public class ToTextComparator implements Comparator<Object>, Serializable {

	private static final long serialVersionUID = -8493047534229566981L;

	private static final Map<Locale, ToTextComparator> cache = new WeakHashMap<Locale, ToTextComparator>();

	private Collator collator;

	private ToTextComparator(Collator collator) {
		this.collator = collator;
	}

	public static ToTextComparator getInstance() {
		return getInstance(Locale.getDefault());
	}

	public static ToTextComparator getInstance(Locale locale) {
		ToTextComparator result = cache.get(locale);
		if (result == null) {
			result = new ToTextComparator(Collator.getInstance(locale));
			cache.put(locale, result);
		}
		return result;
	}

	public int compare(Object o1, Object o2) {
		int result = 0;

		if (o1 != o2) {
			result = collator.compare(o1.toString(), o2.toString());
		}

		return result;
	}
}
